package com.ti.srpglife.world.level;

import java.util.ArrayList;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.ti.srpglife.ai.AI;
import com.ti.srpglife.entity.Unit;

public class Level extends Stage
{
	private TiledMap map;
	private OrthographicCamera cam;
	private SpriteBatch batch;
	private OrthogonalTiledMapRenderer omaprend;
	
	public ArrayList<Unit> units = new ArrayList<Unit>();
	public ArrayList<Unit> selected = new ArrayList<Unit>();
	public ArrayList<AI> ais = new ArrayList<AI>();
	
	private Vector2 cammove;
    
	public Level(String levelpath)
	{
		map = new TmxMapLoader().load(levelpath);
		omaprend = new OrthogonalTiledMapRenderer(map);
		cam = new OrthographicCamera(Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
		cam.setToOrtho(false);
		omaprend.setView(cam);
		batch = new SpriteBatch(256);
		cammove = new Vector2();
	}
	
	//updates on level will update all world effects -> all ai commands -> movement
	public void act(float delta) 
	{
		//should automatically tell all of the actors to act ?
		super.act(delta);
		
		cam.translate(cammove);
		
		for(Unit u : units)
		{
			u.translate(cammove.x*-1,cammove.y*-1);
			//u.draw(batch,1);
		}
	}

	public void render() 
	{
		cam.update();
		
		omaprend.setView(cam);
		
		omaprend.render();
		
		batch.begin();
		for(Unit u : units)
		{
			u.draw(batch, 1);
		}
		batch.end();
		
		cammove.set(0,0);
	}
	
	public void addUnit(Unit u)
	{
		units.add(u);
		addActor(u);
	}
	
	public void moveCam(Vector2 cammove) 
	{
		this.cammove = cammove;
	}

	public void trySelect(int x, int y)
	{
		Actor a = hit(x+(cam.position.x-Gdx.graphics.getWidth()/2), (Gdx.graphics.getHeight()-y)+(cam.position.y-Gdx.graphics.getHeight()/2), false);
		if(a instanceof Unit)
		{
			((Unit)a).select();
			selected.add(((Unit)a));
		}
		else if(a == null)
		{
			for(Unit u : selected)
			{
				u.unselect();
			}
			selected.clear();
		}
	}

	public void tryAct(int x, int y) 
	{
		if(selected.isEmpty())
			return;
		Actor a = hit(x+(cam.position.x-Gdx.graphics.getWidth()/2), (Gdx.graphics.getHeight()-y)+(cam.position.y-Gdx.graphics.getHeight()/2), false);
		
		if(a == null)
		{
			for(Unit u : selected)
			{
				u.commandMove(x+(cam.position.x-Gdx.graphics.getWidth()/2), (Gdx.graphics.getHeight()-y)+(cam.position.y-Gdx.graphics.getHeight()/2));
			}
		}
		else if(a instanceof Unit)
		{
			for(Unit u : selected)
			{
				u.setTarget((Unit)a);
			}
		}
	}
}
